import { useState, useEffect, useRef } from 'react';
import { Table, Space, Button, Modal, Form, Input, InputNumber, Switch } from 'antd';
import { SortOrder } from 'antd/lib/table/interface';
import "../../style/PC_home/index.scss"
interface DataItem {
  key: string;
  name: string;
  previewUrl: string;
  value: number;
  status: '已开启' | '已关闭';
}

const initialData: DataItem[] = Array.from({ length: 20 }, (_, i) => ({
  key: String(i + 1),
  name: `姓名${i + 1}`,
  previewUrl: 'https://via.placeholder.com/150',
  value: (i + 1) * 100,
  status: i % 2 === 0 ? '已开启' : '已关闭',
}));

function TableDemo() {
  const [dataSource, setDataSource] = useState<DataItem[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const formRef = useRef<any>();
  const [editingKey, setEditingKey] = useState('');
  const [sorter, setSorter] = useState<{ field: keyof DataItem, order: SortOrder }>({ field: 'key', order: null });

  // 初始化数据
  useEffect(() => {
    setDataSource(initialData);
  }, []);

  const handleAdd = () => {
    // 添加按钮
    setModalVisible(true);
    setEditingKey('');
  };

  const handleEdit = (record: DataItem) => {
    // 编辑按钮
    setModalVisible(true);
    setEditingKey(record.key);
    formRef.current?.setFieldsValue(record);
  };

  const handleDelete = (record: DataItem) => {
    // 删除按钮
    setDataSource((prev) => prev.filter((item) => item.key !== record.key));
  };

  const handleOk = () => {
    // 确定按钮点击事件
    formRef.current
      .validateFields()
      .then((values: any) => {
        if (editingKey) {
          // 编辑状态下，修改数据源对应的记录
          setDataSource((prev) =>
            prev.map((item) => (item.key === editingKey ? { ...item, ...values } : item)),
          );
        } else {
          // 非编辑状态下，向数据源添加新记录
          setDataSource((prev) => [
            ...prev,
            { key: String(prev.length + 1), ...values },
          ]);
        }
        setModalVisible(false);
        formRef.current?.resetFields();
        setEditingKey('');
      })
      .catch((err: Error) => console.log(err));
  };

  const handleCancel = () => {
    // 取消按钮点击事件
    setModalVisible(false);
    formRef.current?.resetFields();
    setEditingKey('');
  };

  const handleSortChange = (_: any, _2: any, sorter: any) => {
    // 排序变化事件
    setSorter(sorter);
  };

  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      sorter: (a: DataItem, b: DataItem) => a.name.localeCompare(b.name),
      sortOrder: sorter.field === 'name' ? sorter.order : undefined,
    },
    {
      title: '预览图',
      dataIndex: 'previewUrl',
      key: 'previewUrl',
      render: (url: string) => <img src={url} alt="" style={{ width: '50px' }} />,
    },
    {
      title: '数值',
      dataIndex: 'value',
      key: 'value',
      sorter: (a: DataItem, b: DataItem) => a.value - b.value,
      sortOrder: sorter.field === 'value' ? sorter.order : undefined,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string, record: DataItem) => (
        <Switch
          checked={status === '已开启'}
          onChange={() =>
            setDataSource((prev) =>
              prev.map((item) =>
                item.key !== record.key
                  ? item
                  : { ...item, status: item.status === '已开启' ? '已关闭' : '已开启' },
              ),
            )
          }
        />
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_:any, record: DataItem) => (
        // 操作列，包含编辑和删除按钮
        <Space>
          <a onClick={() => handleEdit(record)}>编辑</a>
          <a onClick={() => handleDelete(record)}>删除</a>
        </Space>
      ),
    },
  ];

  return (
    <div className='Tables'>
      {/* 添加按钮 */}
      <Button type="primary" onClick={handleAdd}>
        添加
      </Button>
      {/* 表格组件 */}
      <Table
        dataSource={dataSource}
        columns={columns}
        pagination={{ position: ['bottomCenter'] }}
        onChange={handleSortChange} // 表格变化事件，用于排序
      />
      {/* 弹窗组件 */}
      <Modal
        title={editingKey ? '编辑记录' : '添加记录'}
        open={modalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        {/* 表单组件 */}
        <Form layout="vertical" ref={formRef}>
          <Form.Item label="姓名" name="name" rules={[{ required: true, message: '请输入姓名' }]}>
            <Input placeholder="请输入姓名" />
          </Form.Item>
          <Form.Item
            label="预览图"
            name="previewUrl"
            rules={[{ required: true, message: '请输入预览图' }]}
          >
            <Input placeholder="请输入预览图 URL" />
          </Form.Item>
          <Form.Item label="数值" name="value" rules={[{ required: true, message: '请输入数值' }]}>
            <InputNumber placeholder="请输入数值" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}

export default TableDemo;
